package com.scoresystem.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.scoresystem.common.CommonValue;
import com.scoresystem.dao.ITeacherDao;
import com.scoresystem.exception.UserRepeatException;
import com.scoresystem.model.Teacher;
import com.scoresystem.utils.ResultMapUtil;

public class TeacherDaoImpl extends BaseDaoImpl implements ITeacherDao {

	public TeacherDaoImpl(Connection conn) {
		super(conn);
		this.conn=conn;
	}

	/**
	 * 对查找的重复操作进行封装
	 * @return
	 */
	private Teacher find(String sql){
		try{
			ResultSet rs=this.templateQuery(sql);
			Teacher Teacher=new Teacher();
			if(rs.next()){
				Map<String,String> map=ResultMapUtil.getResultMap(rs);
				try{
					BeanUtils.populate(Teacher, map);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			//如果还有记录，说明名字有重复，向上抛出异常
			if(rs.next())
				throw new UserRepeatException("you have a repeated user");
			else
				return Teacher;
				
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public boolean add(Teacher Teacher) {
		String sql="insert into "+CommonValue.TAB_TEACHER+" (worknum,teaname"
				+ ",major,password)"+"values"+"("+
				"'"+Teacher.getWorknum()+"'"+
				","+"'"+Teacher.getTeaname()+"'"+","
				+"'"+Teacher.getMajor()+"'"+","
				+"'"+Teacher.getPassword()+"'"+")";
		try{
			this.templateUpdate(sql);
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean modify(Teacher teacher) {
		String sql="update teacher set worknum="+"'"+teacher.getWorknum()+"'"+","
				+ " worknum="+"'"+teacher.getWorknum()+"'"+","
				+" teaname="+"'"+teacher.getTeaname()+"'"+","
				+" major="+"'"+teacher.getMajor()+"'"+","
				+" password="+"'"+teacher.getPassword()+"'"+
				" where worknum="+"'"+teacher.getWorknum()+"'";
		try{
			this.templateUpdate(sql);
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean deleteTeachers(String[] teanum) {
		try{
			for(String teanum1:teanum){
				String sql="delete from "+CommonValue.TAB_TEACHER+" where worknum="
						+"'"+teanum1+"'";
				this.templateUpdate(sql);
			}
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Teacher findbyName(String teaname) {
		String sql="select * from "+CommonValue.TAB_TEACHER+" where teaname="+"'"+teaname+"'";
		return find(sql);
	}

	@Override
	public Teacher findbyNum(String teanum) {
		String sql="select * from "+CommonValue.TAB_TEACHER+" where worknum="+"'"+teanum+"'";
		return find(sql);
	}

}
